import * as sass from 'sass'
import fs from 'fs-extra'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import autoprefixer from 'autoprefixer'
import postcss from 'postcss'
import cssnano from 'cssnano'

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

const localesRoot = path.resolve(__dirname, '../../locales')

const contents = fs.readdirSync(localesRoot)
// 遍历每个文件/目录
contents.forEach((name) => {
	const fullPath = path.join(localesRoot, name)

	// 检查是否是目录
	if (fs.statSync(fullPath).isDirectory()) {
		// 检查目录中是否存在指定文件
		const files = fs.readdirSync(fullPath)
		if (files.includes('lang.scss')) {
			console.log(`目录 ${name} 有文件 scss`)

			const scssPath = path.resolve(__dirname, `../../locales/${name}/lang.scss`)

			const scss = sass.compile(scssPath)

			postcss([
				autoprefixer({
					overrideBrowserslist: ['>0.2%', 'last 2 versions', 'Firefox ESR', 'ie >= 10'],
				}),
				cssnano,
			])
				.process(scss.css, { from: scssPath })
				.then((r) => {
					fs.writeFileSync(path.resolve(__dirname, `../../locales/${name}/lang.css`), r.css)
				})
		}
	}
})
